package org.jeecg.common.util;


import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BeanUtil {

    /**
     * 处理文件获取资源路径
     * @return
     */
    public static String handleClassPath(String packPrefix, String path){
        try{
            String[] strs = path.split("(classes/)|(!/)");
            String className = strs[strs.length - 1];
            if(!className.endsWith(".class")){
                return null;
            }
            className = className.replace("/", ".").replace(".class", "");
            if(!className.startsWith(packPrefix)){
                int bindex = className.indexOf(packPrefix);
                className = className.substring(bindex);
            }
            return className;
        } catch (Exception e){
            log.warn("错误的类路径:{}->>{}", packPrefix, path);
            throw new JeecgBootException(e);
        }
    }

    /**
     * 获取类的所有字段
     * @param className
     * @return
     * @throws Exception
     */
    public static List<String> getClassPropertys(String className) throws Exception {
        Object bean = Class.forName(className).newInstance();
        List<String> propertys = getClassPropertys(bean);
        return propertys;
    }

    /**
     * 获取类的所有字段
     * @param bean
     * @return
     * @throws Exception
     */
    public static List<String> getClassPropertys(Object bean) throws Exception {
        List<String> propertys = new ArrayList<>();
        PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(bean.getClass())
                .getPropertyDescriptors();
        for (PropertyDescriptor pd : propertyDescriptors) {
            if(pd.getName().equals("class")){
                continue;
            }
            propertys.add(pd.getName());
        }
        return propertys;
    }
}
